package com.tencreat.mall.controller.app;

import cn.hutool.json.JSONObject;
import com.alibaba.fastjson.JSON;
import com.alipay.api.AlipayApiException;
import com.alipay.api.internal.util.AlipaySignature;
import com.github.binarywang.wxpay.exception.WxPayException;
import com.huifu.adapay.core.AdapayCore;
import com.huifu.adapay.core.util.AdapaySign;
import com.tencreat.common.core.HttpResult;
import com.tencreat.common.core.domain.model.ReqStringListParam;
import com.tencreat.common.core.domain.model.ReqStringParam;
import com.tencreat.common.enums.BalanceBusinessType;
import com.tencreat.common.enums.BalanceTypeEnum;
import com.tencreat.common.enums.mall.AllEnum;
import com.tencreat.common.utils.DictUtils;
import com.tencreat.common.utils.LianSignUtils;
import com.tencreat.common.utils.RabbitSendUtils;
import com.tencreat.common.utils.SecurityUtils;
import com.tencreat.domain.account.AccountWithdrawAudit;
import com.tencreat.domain.account.MallUser;
import com.tencreat.domain.mall.BalanceChange;
import com.tencreat.domain.mall.MallPaySetting;
import com.tencreat.domain.mall.dto.CashIntegralPayDTO;
import com.tencreat.service.account.IAccountWithdrawAuditService;
import com.tencreat.service.account.IMallUserService;
import com.tencreat.service.mall.IBalanceChangeService;
import com.tencreat.service.mall.IMallPaySettingService;
import com.tencreat.service.mall.IPayService;
import com.tencreat.service.mall.impl.PayServiceImpl;
import com.upay.sdk.FastJsonUtils;
import com.upay.sdk.exception.HmacVerifyException;
import com.upay.sdk.exception.ResponseException;
import com.upay.sdk.exception.UnknownException;
import com.upay.sdk.executer.ResultListenerAdpater;
import com.upay.sdk.onlinepay.executer.OnlinePayOrderExecuter;
import com.upay.sdk.transferDomestic.executer.TransferDomesticOrderExecuter;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import javax.annotation.Resource;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.*;

/**
 * 支付处理控制器
 *
 * @author huang wei
 * @version 1.0
 * @date 2021/9/2 16:20
 */
@Slf4j
@RestController
@Api(tags = "91-支付相关")
@RequestMapping("/pay")
public class ApiPayController {
    private final static Logger logger = LoggerFactory.getLogger("sys-pay");
    @Resource
    private IPayService iPayService;//支付处理类
    @Autowired
    private IAccountWithdrawAuditService accountWithdrawAuditService;//提现记录
    @Autowired
    private IMallUserService mallUserService;//用户
    @Autowired
    private IBalanceChangeService balanceChangeService;//余额变动
    @Autowired
    private RabbitSendUtils rabbitSendUtils;
    @Autowired
    private IMallPaySettingService mallPaySettingService;//支付设置

    /**
     * 调用统一下单接口，并组装生成支付所需参数对象.  微信支付
     *
     * @param
     *
     * @return 返回 {@link com.github.binarywang.wxpay.bean.order}包下的类对象
     */
    @ApiOperation(value = "微信统一下单，并组装所需支付参数")
    @PostMapping("/wx/createOrder")
    public HttpResult<?> createWxOrder(@RequestBody ReqStringListParam reqStringListParam) throws WxPayException {
        if (reqStringListParam.getId().size()<1) {
            return HttpResult.error("订单号不能为空!");
        }
        Object wxOrder = null;
        if(reqStringListParam.getId().size() == 1){
            wxOrder = iPayService.createWxOrder(new ReqStringParam().setCommon(reqStringListParam.getId().get(0)).setTradeType(reqStringListParam.getTradeType()));
        }else {

            wxOrder = iPayService.createWxOrders(reqStringListParam.getId(),reqStringListParam.getTradeType());
        }
        return HttpResult.ok(wxOrder);
    }

    /**
     * 调用统一下单接口，并组装生成支付所需参数对象.
     *
     * @param commons 订单号集合
     * @return 返回 {@link com.github.binarywang.wxpay.bean.order}包下的类对象
     */
    @ApiOperation(value = "微信多订单组合支付统一下单，并组装所需支付参数")
    @PostMapping("/wx/createOrders")
    public HttpResult<?> createWxOrders(@RequestBody List<String> commons,String tradeType) throws WxPayException {
        if (commons.isEmpty()) {
            return HttpResult.error("订单号不能为空!");
        }
        return HttpResult.ok(iPayService.createWxOrders(commons,tradeType));
    }

    @ApiOperation(value = "微信支付回调通知处理")
    @PostMapping("/wx/notify/order")
    @ApiIgnore
    public HttpResult<?> parseWxOrderNotifyResult(@RequestBody String xmlData) throws WxPayException {
        return HttpResult.ok(iPayService.parseWxOrderNotifyResult(xmlData));
    }

    /**
     * 支付宝支付(证书)
     */
    @ApiOperation(value = "支付宝支付")
    @PostMapping("/alipay/createAliPayCertificateOrder")
    public HttpResult<?> createAliPayCertificateOrder(@RequestBody ReqStringParam param) throws AlipayApiException {
        if (StringUtils.isBlank(param.getCommon())) {
            return HttpResult.error("订单号不能为空!");
        }
        iPayService.createAliPayCertificateOrder(param);
        return HttpResult.ok();
    }

    @ApiOperation(value = "支付宝H5支付")
    @PostMapping("/alipay/createAliPayH5Order")
    public HttpResult<?> createAliPayH5Order(@RequestBody ReqStringListParam reqStringListParam) throws AlipayApiException {
        if (reqStringListParam.getId().size() < 1) {
            return HttpResult.error("订单号不能为空!");
        }
        String aliPayOrder = null;
        if(reqStringListParam.getId().size() == 1){
            aliPayOrder = iPayService.createAliPayH5Order(new ReqStringParam().setCommon(reqStringListParam.getId().get(0)));
        }
        return HttpResult.ok(aliPayOrder);
    }


    /**
     * 支付宝H5支付回调
     */
    @ApiOperation(value = "支付宝H5支付回调")
    @PostMapping("/alipay/noticeAliH5pay")
    public String noticeH5Alipay(HttpServletRequest request) throws AlipayApiException {
        //获取支付宝POST过来反馈信息
        Map<String, String> params = new HashMap<>(16);
        Map requestParams = request.getParameterMap();
//        log.info("回调参数-----{}",requestParams);
        for (Iterator iter = requestParams.keySet().iterator(); iter.hasNext(); ) {
            String name = (String) iter.next();
            String[] values = (String[]) requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i] : valueStr + values[i] + ",";
            }
            //乱码解决，这段代码在出现乱码时使用。
            //valueStr = new String(valueStr.getBytes("ISO-8859-1"), "utf-8");
            params.put(name, valueStr);
        }
        //切记alipaypublickey是支付宝的公钥，请去open.alipay.com对应应用下查看。
        //boolean AlipaySignature.rsaCheckV1(Map<String, String> params, String publicKey, String charset, String sign_type)
        Map<String, String> aliPayConfigMap = PayServiceImpl.aliPayConfig2();
        boolean flag = AlipaySignature.rsaCheckV1(params, aliPayConfigMap.get("ALIPAY_PUBLIC_KEY"), "UTF-8", "RSA2");
        log.info("支付宝回调状态：{}，回调参数{}",flag, new JSONObject(params).toString());
        iPayService.parseAliPayOrderNotifyResult(params, flag);

        return flag?"success":"failure";
    }


    /**
     * 支付宝支付（true）
     */
    @ApiOperation(value = "支付宝支付")
    @PostMapping("/alipay/createAliPayOrder")
    public HttpResult<?> createAliPayOrder(@RequestBody ReqStringListParam reqStringListParam) throws AlipayApiException {
        if (reqStringListParam.getId().size()<1) {
            return HttpResult.error("订单号不能为空!");
        }
        String aliPayOrder = null;
        if(reqStringListParam.getId().size() == 1){
            aliPayOrder = iPayService.createAliPayOrder(new ReqStringParam().setCommon(reqStringListParam.getId().get(0)));
        }else {
            aliPayOrder = iPayService.createAliPayOrders(reqStringListParam.getId());
        }
        return HttpResult.ok(aliPayOrder);
    }

    /**
     * 支付宝支付（true）多订单组合支付
     */
    @ApiOperation(value = "支付宝支付多订单组合支付")
    @PostMapping("/alipay/createAliPayOrders")
    public HttpResult<?> createAliPayOrders(@RequestBody List<String> commons) throws AlipayApiException {
        if (commons.size() == 0) {
            return HttpResult.error("订单号不能为空!");
        }
        return HttpResult.ok(iPayService.createAliPayOrders(commons));
    }

    /**
     * 余额支付
     */
/*    @ApiOperation(value = "余额支付")
    @PostMapping("/balance/createBalanceOrder")
    public HttpResult<?> createBalanceOrder(@RequestBody ReqStringParam payParam) {
        if (StringUtils.isEmpty(payParam.getCommon())) {
            return HttpResult.error("订单号不能为空!");
        }
        // 传入用户ID，加锁
        payParam.setUuid(SecurityUtils.getLoginUser().getAccountLogin().getUuid());
        iPayService.balancePay(payParam);

        return HttpResult.ok();

    }*/


    /**
     * 描述信息 消费券支付
     * @Author yaoruiqi
     * @Date: 2023/10/09 10:30
     */
    @ApiOperation(value = "消费券支付")
    @PostMapping("/balance/createBalanceOrder")
    public HttpResult<?> createConsumerRollOrder(@RequestBody ReqStringParam payParam) {
        if (StringUtils.isEmpty(payParam.getCommon())) {
            return HttpResult.error("订单号不能为空!");
        }
        // 传入用户ID，加锁
        payParam.setUuid(SecurityUtils.getLoginUser().getAccountLogin().getUuid());
        iPayService.consumerRollPay(payParam);

        return HttpResult.ok();

    }

    /**
     * 支付宝支付回调（证书）
     */
    @ApiOperation(value = "支付宝支付回调（证书）")
    @PostMapping("/alipay/noticeAlipayCertificate")
    @ApiIgnore
    public HttpResult<?> noticeAlipayCertificate(HttpServletRequest request) throws AlipayApiException {
        //获取支付宝POST过来反馈信息
        Map<String, String> params = new HashMap<String, String>();
        Map requestParams = request.getParameterMap();
        for (Iterator iter = requestParams.keySet().iterator(); iter.hasNext(); ) {
            String name = (String) iter.next();
            String[] values = (String[]) requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i] : valueStr + values[i] + ",";
            }
            //乱码解决，这段代码在出现乱码时使用。
            //valueStr = new String(valueStr.getBytes("ISO-8859-1"), "utf-8");
            params.put(name, valueStr);
        }
        //切记alipayPublicCertPath是应用公钥证书路径，请去open.alipay.com对应应用下载。
        //boolean AlipaySignature.rsaCertCheckV1(Map<String, String> params, String publicKeyCertPath, String charset,String signType)
        Map<String, String> aliPayConfigMap = PayServiceImpl.aliPayConfig();

        boolean flag = AlipaySignature.rsaCertCheckV1(params, aliPayConfigMap.get("alipay_cert_path"), "utf-8", "RSA2");
        return HttpResult.ok();
    }

    /**
     * 支付宝支付回调
     */
    @ApiOperation(value = "支付宝支付回调")
    @PostMapping("/alipay/noticeAlipay")
    @ApiIgnore
    public String noticeAlipay(HttpServletRequest request) throws AlipayApiException {
        //获取支付宝POST过来反馈信息
        Map<String, String> params = new HashMap<>(16);
        Map requestParams = request.getParameterMap();
        for (Iterator iter = requestParams.keySet().iterator(); iter.hasNext(); ) {
            String name = (String) iter.next();
            String[] values = (String[]) requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i] : valueStr + values[i] + ",";
            }
            //乱码解决，这段代码在出现乱码时使用。
            //valueStr = new String(valueStr.getBytes("ISO-8859-1"), "utf-8");
            params.put(name, valueStr);
        }
        //切记alipaypublickey是支付宝的公钥，请去open.alipay.com对应应用下查看。
        //boolean AlipaySignature.rsaCheckV1(Map<String, String> params, String publicKey, String charset, String sign_type)
        Map<String, String> aliPayConfigMap = PayServiceImpl.aliPayConfig();
        boolean flag = AlipaySignature.rsaCheckV1(params, aliPayConfigMap.get("ALIPAY_PUBLIC_KEY"), "UTF-8", "RSA2");
        logger.info("支付宝回调状态：{}，回调参数{}",flag, new JSONObject(params).toString());
        iPayService.parseAliPayOrderNotifyResult(params, flag);
        return flag?"success":"failure";
    }


    /**
     * 支付宝退款
     */
    @ApiOperation(value = "支付宝退款")
    @PostMapping("/alipay/alipayTradeRefund")
    public HttpResult<?> alipayTradeRefund(@RequestBody ReqStringParam param) throws AlipayApiException {
        if (StringUtils.isBlank(param.getCommon())) {
            return HttpResult.error("订单号不能为空!");
        }
        return HttpResult.ok(iPayService.alipayTradeRefund(param));
    }

    /**
     * <pre>
     * 微信支付-申请退款
     * 详见 https://pay.weixin.qq.com/wiki/doc/api/jsapi.php?chapter=9_4
     * 接口链接：https://api.mch.weixin.qq.com/secapi/pay/refund
     * </pre>
     *
     * @param param 请求对象
     * @return 退款操作结果
     */
    @ApiOperation(value = "退款")
    @PostMapping("/wx/refundWx")
    public HttpResult<?> refundWx(@RequestBody ReqStringParam param) throws WxPayException {
        if (StringUtils.isBlank(param.getCommon())) {
            return HttpResult.error("订单号不能为空!");
        }
        return HttpResult.ok(iPayService.refundWx(param));
    }



/*    *//**
     * 调用统一下单接口，并组装生成支付所需参数对象.
     *
     * @param
     *
     * @return 返回 {@link com.github.binarywang.wxpay.bean.order}包下的类对象
     */
    @ApiOperation(value = "首信易统一下单，并组装所需支付参数")
   // @PostMapping("/sxy/createBankOrder")
    public HttpResult<?> createBankOrder(@RequestBody ReqStringParam param) {
        if (param.getCommon() == null) {
            return HttpResult.error("订单号不能为空!");
        }

        return HttpResult.ok(iPayService.sxyBankPay(param));
    }

    /**
     * 协议支付第二步  下单确认
     *
     * @param
     *
     * @return 返回 {@link com.github.binarywang.wxpay.bean.order}包下的类对象
     */
    @ApiOperation(value = "首信易 协议支付第二步  下单确认")
   // @PostMapping("/sxy/paymentBank")
    public HttpResult<?> paymentBank(@RequestBody ReqStringParam param) {
        if (param.getCommon() == null) {
            return HttpResult.error("订单号不能为空!");
        }
        com.alibaba.fastjson.JSONObject data = iPayService.paymentBank(param);
        if (!data.getString("status").equals("SUCCESS")){
            return HttpResult.error(data.getString("msg"));
        }

        return HttpResult.ok(data);
    }

    @ApiOperation(value = "首信易支付回调数据")
    //@PostMapping("/sxy/callback")
    @ApiIgnore
    public void sxyCallback(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        log.info("首信易回调数据："+req);
        OnlinePayOrderExecuter executer = new OnlinePayOrderExecuter();
        try{
            com.alibaba.fastjson15.JSONObject json = FastJsonUtils.convert(req.getInputStream());
            json.put("encryptKey",req.getHeader("encryptKey"));
            json.put("merchantId",req.getHeader("merchantId"));
            executer.bothCipherCallback(json, new ResultListenerAdpater() {

                @Override
                public void success(com.alibaba.fastjson15.JSONObject jsonObject) {
                    log.info("支付成功！{}",jsonObject.toJSONString());
                    try {
                        if (jsonObject.getString("status") != null && jsonObject.getString("status").equals("SUCCESS")) {
                            iPayService.noticeSxy(jsonObject.getString("requestId"), jsonObject.getString("serialNumber"));
                        }
                    } catch (InterruptedException e) {
                        log.info("业务错误{}",e.toString());
                    }
                }

                @Override
                public void failure(com.alibaba.fastjson15.JSONObject jsonObject) {
                    log.info("支付失败！{}",jsonObject.toJSONString());
                }
            });
        }
        catch(ResponseException e){
            log.error("响应异常{}",e.toString());
        }
        catch(HmacVerifyException e){
            log.error("签名验证异常{}",e.toString());
        }
        catch(UnknownException e){
            log.error("未知异常{}",e.toString());
        }

        PrintWriter out = resp.getWriter();

        out.print("SUCCESS");
    }

    /**
     * 调用统一下单接口，并组装生成支付所需参数对象.
     *
     * @param
     *
     * @return 返回 {@link com.github.binarywang.wxpay.bean.order}包下的类对象
     */
    @ApiOperation(value = "Adapay统一下单，并组装所需支付参数")
   // @PostMapping("/adapay/alipayH5")
    public HttpResult<?> adapayAlipayH5(@RequestBody ReqStringParam param) throws Exception{
        if (param.getCommon() == null) {
            return HttpResult.error("订单号不能为空!");
        }

        return HttpResult.ok(iPayService.adapayAlipayH5(param));
    }

    @ApiOperation(value = "Adapay支付回调")
   // @PostMapping("/adapay/callback")
    @ApiIgnore
    public HttpResult<?> callback(HttpServletRequest request) {
        try {
            //验签请参data
            String data = request.getParameter("data");
            //验签请参sign
            String sign = request.getParameter("sign");
            //验签标记
            boolean checkSign;
            //验签请参publicKey
            String publicKey = AdapayCore.PUBLIC_KEY;
            log.info("验签请参：data={}sign={}",data,sign);
            //验签
            checkSign = AdapaySign.verifySign(data, sign, publicKey);
            if(checkSign){
                //验签成功逻辑
                log.info("成功返回数据data:"+data);
                com.alibaba.fastjson.JSONObject jsonObject = JSON.parseObject(data);
                if (jsonObject.get("status") != null && jsonObject.get("status").equals("succeeded")) {
                    iPayService.noticeSxy(jsonObject.getString("order_no"), jsonObject.getString("id"));
                }

                return HttpResult.ok();
            }else {
                //验签失败逻辑
                log.info("失败返回数据data:"+data);
                return HttpResult.error();
            }
        }catch (Exception e){
            log.error("异步回调开始，参数，request={}",request);

            return HttpResult.error();
        }
    }


    /**
     * 调用统一下单接口，并组装生成支付所需参数对象.
     *
     * @param
     *
     * @return 返回 {@link com.github.binarywang.wxpay.bean.order}包下的类对象
     */
/*    @ApiOperation(value = "连连统一下单，并组装所需支付参数")
    @PostMapping("/lianLian/bankPay")
    public HttpResult<?> createLianBankOrder(@RequestBody ReqStringParam param) {
        if (param.getCommon() == null) {
            return HttpResult.error("订单号不能为空!");
        }

        return HttpResult.ok(iPayService.lianLianBankPay(param));
    }*/
    @ApiOperation(value = "连连支付回调")
   // @PostMapping("/lianLian/callback")
    @ApiIgnore
    public Object lianLianCallback(HttpServletRequest request) {
        try {
            com.alibaba.fastjson15.JSONObject convert = FastJsonUtils.convert(request.getInputStream());
            log.info("连连回调数据--------"+convert.toJSONString());
            //验签请参sign
            String sign = convert.getString("sign");
            // 生成签名数据
            convert.remove("sign");
            Map map = JSON.parseObject(convert.toJSONString());
            Map<String, Object> sortMap = new TreeMap<String, Object>(new Comparator<String>() {

                @Override
                public int compare(String o1, String o2) {

                    return ((String) o1).compareTo((String) o2);
                }
            });

            sortMap.putAll(map);
            String s1 = sortMap.toString().replaceAll(", ", "&");
            s1 = s1.substring(1, s1.length()-1);
            String publickKey = DictUtils.getDictValue("lianlian_pay","publick_key");
            boolean verify = LianSignUtils.verify(s1, publickKey, sign);
            JSONObject jsonObject = new JSONObject();
            if (!verify){
                log.info("验签失败------------数据：{},签名：{}",s1,sign);
                jsonObject.put("ret_code","99999");
                jsonObject.put("ret_msg","验签失败");

                return jsonObject;
            }
            iPayService.noticeSxy(convert.getString("no_order"), convert.getString("oid_paybill"));

            jsonObject.put("ret_code","0000");
            jsonObject.put("ret_msg","交易成功");

            return jsonObject;
        }catch (Exception e){
            log.error("异步回调开始，参数，request={}",request);

            return HttpResult.error();
        }
    }

    @ApiOperation(value = "连连代付回调")
    //@PostMapping("/lianLian/cipherCallback")
    @ApiIgnore
    public Object lianLianCipherCallback(HttpServletRequest request) {
        try {
            String publickKey = DictUtils.getDictValue("lianlian_pay","publick_key");
            com.alibaba.fastjson15.JSONObject convert = FastJsonUtils.convert(request.getInputStream());
            log.info("进入连连代付回调--------"+convert.toJSONString());
            //验签请参sign
            String sign = convert.getString("sign");
            // 生成签名数据
            convert.remove("sign");
            Map map = JSON.parseObject(convert.toJSONString());
            Map<String, Object> sortMap = new TreeMap<String, Object>(new Comparator<String>() {

                @Override
                public int compare(String o1, String o2) {

                    return ((String) o1).compareTo((String) o2);
                }
            });

            sortMap.putAll(map);
            String s1 = sortMap.toString().replaceAll(", ", "&");
            s1 = s1.substring(1, s1.length()-1);
            boolean verify = LianSignUtils.verify(s1, publickKey, sign);
            JSONObject jsonObject = new JSONObject();
            if (!verify){
                log.info("验签失败------------数据：{},签名：{}",s1,sign);
                jsonObject.put("ret_code","99999");
                jsonObject.put("ret_msg","验签失败");

                return jsonObject;
            }
            AccountWithdrawAudit withdrawAudit = accountWithdrawAuditService.lambdaQuery().eq(AccountWithdrawAudit::getSn, convert.getString("no_order")).one();
            if (withdrawAudit != null && withdrawAudit.getReceiptStatus() == 0) {
                // 转账成功
                withdrawAudit.setReceiptStatus(1);
                withdrawAudit.setUpdateTime(LocalDateTime.now());
                withdrawAudit.setPaySn(convert.getString("oid_paybill"));

                accountWithdrawAuditService.updateById(withdrawAudit);
            }

            jsonObject.put("ret_code","0000");
            jsonObject.put("ret_msg","交易成功");

            return jsonObject;
        }catch (Exception e){
            log.error("异步回调开始，参数，request={}",request);

            return HttpResult.error();
        }
    }

    @ApiOperation(value = "首信易代付回调数据")
    //@PostMapping("/sxy/cipherCallback")
    @ApiIgnore
    public void cipherCallback(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException{
        log.info("首信易代付回调数据："+req);
        TransferDomesticOrderExecuter executer = new TransferDomesticOrderExecuter();
        try{

            com.alibaba.fastjson15.JSONObject json = FastJsonUtils.convert(req.getInputStream());
            json.put("encryptKey",req.getHeader("encryptKey"));
            json.put("merchantId",req.getHeader("merchantId"));

            executer.bothCipherCallback(json, new ResultListenerAdpater() {

                @Override
                public void success(com.alibaba.fastjson15.JSONObject jsonObject) {
                    log.info("转账成功！{}",jsonObject.toJSONString());
                    AccountWithdrawAudit withdrawAudit = accountWithdrawAuditService.lambdaQuery().eq(AccountWithdrawAudit::getSn, jsonObject.getString("requestId")).one();
                    if (withdrawAudit != null && withdrawAudit.getReceiptStatus() == 0) {
                        // 转账成功
                        withdrawAudit.setReceiptStatus(1);
                        withdrawAudit.setUpdateTime(LocalDateTime.now());
                        withdrawAudit.setPaySn(jsonObject.getString("serialNumber"));

                        accountWithdrawAuditService.updateById(withdrawAudit);
                    }

                }

                @Override
                public void failure(com.alibaba.fastjson15.JSONObject jsonObject) {
                    log.info("转账失败！{}",jsonObject);
                    log.info(jsonObject.toJSONString());
                    AccountWithdrawAudit withdrawAudit = accountWithdrawAuditService.lambdaQuery().eq(AccountWithdrawAudit::getSn, jsonObject.getString("requestId")).one();
                    if (withdrawAudit != null && withdrawAudit.getReceiptStatus() == 0) {
                        // 将余额加入
                        BalanceChange balanceChange = balanceChangeService.getById(withdrawAudit.getBalanceId());
                        MallUser one = mallUserService.lambdaQuery().eq(MallUser::getUuid, balanceChange.getUuid()).one();
                        rabbitSendUtils.sendBalanceMessage(one.getUuid(),balanceChange.getChangAmount().abs(),AllEnum.BalanceChangeTypeEnums.INCOME.getType(), BalanceBusinessType.WITHDRAW_FAIL,"转账失败",balanceChange.getId()+"", BalanceTypeEnum.BALANCE);


                        // 转账失败
                        withdrawAudit.setReceiptStatus(2);
                        withdrawAudit.setUpdateTime(LocalDateTime.now());
                        withdrawAudit.setRemarks(jsonObject.getString("errorMessage"));
                        withdrawAudit.setPaySn(jsonObject.getString("serialNumber"));

                        accountWithdrawAuditService.updateById(withdrawAudit);
                    }
                }

                @Override
                public void processing(com.alibaba.fastjson15.JSONObject jsonObject) {
                    log.info("转账处理中！{}",jsonObject.toJSONString());
                }
            });
        }
        catch(ResponseException e){
            log.error("响应异常,{}",e.toString());
        }
        catch(HmacVerifyException e){
            log.error("签名验证异常,{}",e.toString());
        }
        catch(UnknownException e){
            log.error("未知异常,{}",e.toString());
        }

        PrintWriter out = resp.getWriter();

        out.print("SUCCESS");
    }

    /**
     * 快捷支付回调
     *
     * @param map
     * @return 结果
     * @Author lx
     * @Date: 2022/07/06 08:04
     */
    @ApiOperation(value = "杉德支付回调")
    @PostMapping("sandPayNoticeBank")
    @ApiIgnore
    public Map<String, String> sandPayNoticeBank(@RequestParam Map<String, String> map) {
        log.info("杉德支付回调--------------");
        return iPayService.sandPayNoticeBank(map);
    }

    @ApiOperation(value = "杉德银行卡快捷支付")
    @PostMapping(value = "/sandPayCreateOrderBank")
    public HttpResult<com.alibaba.fastjson.JSONObject> sandPayCreateOrderBank(@RequestBody ReqStringParam param, HttpServletResponse response) {
        return HttpResult.ok(iPayService.sandPayCreateOrderBank(param.getCommon()));
    }

    @ApiOperation(value = "杉德 发送支付短信验证码")
    @PostMapping(value = "/sandGetKaptcha")
    public HttpResult<Object> sandGetKaptcha(@RequestBody ReqStringParam param, HttpServletResponse response) {
        return HttpResult.ok(iPayService.sandGetKaptcha(param));
    }

    @ApiOperation(value = "杉德 支付下单")
    @PostMapping(value = "/sandPay")
    public HttpResult<Object> sandPay(@RequestBody ReqStringParam param, HttpServletResponse response) {
        return HttpResult.ok(iPayService.sandPay(param));
    }

    @ApiOperation(value="查询支付设置列表")
    @ApiImplicitParam(value = "类型，0|商品购买,1|余额充值", name = "type")
    @GetMapping("/setting/list")
    public HttpResult<List<MallPaySetting>> list(Integer type) {
        List<MallPaySetting> list = mallPaySettingService.lambdaQuery().eq(MallPaySetting::getType, type).orderByAsc(MallPaySetting::getSort).list();
        list.forEach(item -> {
            if (item.getCompany() != null) {
                item.setCompanyValue(item.getCompany().getValue());
            }
            if (item.getPayType() != null) {
                item.setPayTypeValue(item.getPayType().getValue());
            }
        });
        return HttpResult.ok(list);
    }
}
